﻿/*
 * Created by SharpDevelop.
 * User: Vendan
 * Date: 3/7/2012
 * Time: 12:36 AM
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
using System;
using System.Diagnostics;
using System.Drawing;
using System.Threading;
using System.Collections.Generic;
using System.Windows.Forms;

namespace GMusic
{
	public sealed class NotificationIcon
	{
		private NotifyIcon notifyIcon;
		private ContextMenu notificationMenu;
		private GMusicPlayer player;
		
		#region Initialize icon and menu
		public NotificationIcon()
		{
			notifyIcon = new NotifyIcon();
			notificationMenu = new ContextMenu(InitializeMenu());
			
			notifyIcon.DoubleClick += IconDoubleClick;
			notifyIcon.Click += new EventHandler(notifyIcon_Click);
			System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(NotificationIcon));
			notifyIcon.Icon = (Icon)resources.GetObject("GMusic");
			notifyIcon.ContextMenu = notificationMenu;
			notifyIcon.BalloonTipTitle = "GMMP";
			notifyIcon.BalloonTipText = "Not Playing";
			notifyIcon.Visible = true;
			
			player = new GMusicPlayer();
			player.SongStart += new delSongStart(player_SongStart);
			player.SongEnd += new delSongEnd(player_SongEnd);
			
			if(GMusic.Default.AutoLogin)
			{
				Login(GMusic.Default.Account, GMusic.Default.Password);
			}
			
		}
		
		void Login(string account, string password)
		{
			notifyIcon.ShowBalloonTip(10000, "GMMP", "Attempting Login", ToolTipIcon.Info);
			try
			{
				player.Login(account, password);
			}
			catch(Exception e)
			{
				if(e.Message == "Invalid Login")
				{
					notifyIcon.ShowBalloonTip(10000, "GMMP", "Login Failed", ToolTipIcon.Error);
					notifyIcon.ContextMenu.MenuItems["tracks"].MenuItems.Clear();
					notifyIcon.ContextMenu.MenuItems["tracks"].Text = "Not Logged In";
					notifyIcon.ContextMenu.MenuItems["login"].Text = "Login";
					notifyIcon.ContextMenu.MenuItems["login"].Click -= menuLogoutClick;
					notifyIcon.ContextMenu.MenuItems["login"].Click += menuLoginClick;
					GMusic.Default.Account = "";
					GMusic.Default.Password = "";
					GMusic.Default.AutoLogin = false;
					GMusic.Default.Save();
					return;
				}
			}
			player.GetTracks();
			notifyIcon.BalloonTipText = "Not Playing";
			
			notifyIcon.ContextMenu.MenuItems["tracks"].MenuItems.Clear();
			foreach(KeyValuePair<string, Dictionary<string, Dictionary<int, Tuple<string, string>>>> artist in player.tracks)
			{
				notifyIcon.ContextMenu.MenuItems["tracks"].MenuItems.Add(artist.Key);
				foreach(KeyValuePair<string, Dictionary<int, Tuple<string, string>>> album in artist.Value)
				{
					notifyIcon.ContextMenu.MenuItems["tracks"].MenuItems[notifyIcon.ContextMenu.MenuItems[0].MenuItems.Count-1].MenuItems.Add(album.Key, menuAlbumClick);
				}
			}
			notifyIcon.ContextMenu.MenuItems["tracks"].Text = "Play";
			notifyIcon.ShowBalloonTip(10000, "GMMP", "Login Successful\nTracks Loaded", ToolTipIcon.Info);
		}
		
		private MenuItem[] InitializeMenu()
		{
			MenuItem login = new MenuItem("Login", menuLoginClick);
			login.Name = "login";
			MenuItem tracks = new MenuItem("Not Logged In");
			tracks.Name = "tracks";
			MenuItem playing = new MenuItem("Not Playing");
			playing.Name = "playing";
			MenuItem[] menu = new MenuItem[] {
				tracks,
				new MenuItem("-"),
				playing,
				new MenuItem("-"),
				login,
				new MenuItem("Exit", menuExitClick)
			};
			return menu;
		}
		#endregion
		
		#region Main - Program entry point
		/// <summary>Program entry point.</summary>
		/// <param name="args">Command Line Arguments</param>
		[STAThread]
		public static void Main(string[] args)
		{
			Application.EnableVisualStyles();
			Application.SetCompatibleTextRenderingDefault(false);
			
			if (GMusic.Default.UpdateRequired)
			{
				GMusic.Default.Upgrade();
				GMusic.Default.UpdateRequired = false;
				GMusic.Default.Save();
			}
			
			bool isFirstInstance;
			
			// Please use a unique name for the mutex to prevent conflicts with other programs
			using (Mutex mtx = new Mutex(true, "GMusic", out isFirstInstance)) {
				if (isFirstInstance) {
					NotificationIcon notificationIcon = new NotificationIcon();
					Application.Run();
					notificationIcon.notifyIcon.Dispose();
				} else {
					// The application is already running
					// TODO: Display message box or change focus to existing application instance
				}
			} // releases the Mutex
			
		}
		#endregion
		
		#region Event Handlers
		private void menuLoginClick(object sender, EventArgs e)
		{
			GMusicLogin login = new GMusicLogin();
			login.Login += new delLogin(login_Login);
			login.Show();
		}

		private void menuLogoutClick(object sender, EventArgs e)
		{
			GMusic.Default.Account = "";
			GMusic.Default.Password = "";
			GMusic.Default.AutoLogin = false;
			GMusic.Default.Save();
			player.Logout();
			player.stop();
			notifyIcon.ContextMenu.MenuItems["tracks"].MenuItems.Clear();
			notifyIcon.ContextMenu.MenuItems["tracks"].Text = "Not Logged In";
			notifyIcon.ContextMenu.MenuItems["login"].Text = "Login";
			notifyIcon.ContextMenu.MenuItems["login"].Click -= menuLogoutClick;
			notifyIcon.ContextMenu.MenuItems["login"].Click += menuLoginClick;
		}

		void login_Login(string account, string password, bool saveInfo)
		{
			if(saveInfo)
			{
				GMusic.Default.Account = account;
				GMusic.Default.Password = password;
				GMusic.Default.AutoLogin = true;
				GMusic.Default.Save();
			}
			notifyIcon.ContextMenu.MenuItems["login"].Text = "Logout";
			notifyIcon.ContextMenu.MenuItems["login"].Click -= menuLoginClick;
			notifyIcon.ContextMenu.MenuItems["login"].Click += menuLogoutClick;
			Login(account, password);
		}
		
		private void menuExitClick(object sender, EventArgs e)
		{
			Application.Exit();
		}
		
		private void IconDoubleClick(object sender, EventArgs e)
		{
			player.playPause();
		}
		
		private void menuAlbumClick(object sender, EventArgs e)
		{
			player.playAlbum(((MenuItem)((MenuItem)sender).Parent).Text, ((MenuItem)sender).Text);
		}
		
		void notifyIcon_Click(object sender, EventArgs e)
		{
			if(((MouseEventArgs)e).Button == MouseButtons.Left)
				notifyIcon.ShowBalloonTip(10000);
		}

		void player_SongEnd()
		{
			notifyIcon.ContextMenu.MenuItems["playing"].Text = "Not Playing";
			notifyIcon.BalloonTipText = "Not Playing";
		}

		void player_SongStart(string name, string artist, string album)
		{
			notifyIcon.ContextMenu.MenuItems["playing"].Text = artist + " - " + name;
			notifyIcon.BalloonTipText = "Playing: " + artist + " - " + name;
		}
		#endregion
	}
}
